package com.wiwf.model.mqtt.service;

import java.util.Date;
import java.util.LinkedHashMap;

import javax.annotation.Resource;

import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.gitee.fastmybatis.core.query.Query;
import com.wiwf.model.mapper.business.bean.MqBkMsgEntity;
import com.wiwf.model.mapper.business.dao.MqBkMsgMapper;

/**
 * @author kehui
 */
@Service("backMqttReceiverImpl")
public class BackMqttReceiverImpl implements MessageHandler {

    @Resource
    private MqBkMsgMapper bkMsgMapper;
    
	@Override
	public void handleMessage(Message<?> message) throws MessagingException {
		String msgByte = message.getPayload().toString();
		
		JSONObject jsonObject = JSONObject.parseObject(msgByte.toString());
		String id = jsonObject.getString("id");
		String type = jsonObject.getString("type");
		String msg = jsonObject.getString("msg");
		Date date = new Date();

		Query query = new Query();
		LinkedHashMap<String, Object> allEqMap = new LinkedHashMap<String, Object>();
		
		if(msg.startsWith("frame=") && type.equals("txt")) {
			allEqMap.put("msg_id", id);
			allEqMap.put("type", "txt");
			query.allEq(allEqMap);
			// 删除其他消息
			bkMsgMapper.deleteByQuery(query);
		}
		if(type.equals("img")) {
			allEqMap.put("msg_id", id);
			query.allEq(allEqMap);
			// 删除其他消息
			bkMsgMapper.deleteByQuery(query);
		}
		if(msg.startsWith("video:")) {
			return;
		}
		bkMsgMapper.save(new MqBkMsgEntity(id, type, msg, date));
	}

}
